package com.xiaoye.qbproject.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoye.qbproject.domain.QbSubjectSubscription;
import com.xiaoye.qbproject.exception.NoLoginException;
import com.xiaoye.qbproject.exception.ServiceException;
import com.xiaoye.qbproject.service.QbSubjectSubscriptionService;
import com.xiaoye.qbproject.mapper.QbSubjectSubscriptionMapper;
import com.xiaoye.qbproject.service.web.TokenService;
import com.xiaoye.qbproject.vo.SubjectSubscriptionVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @description 针对表【QB_SUBJECT_SUBSCRIPTION(情报专题订阅)】的数据库操作Service实现
 * @createDate 2025-01-14 22:43:49
 */
@Service
public class QbSubjectSubscriptionServiceImpl extends ServiceImpl<QbSubjectSubscriptionMapper, QbSubjectSubscription>
        implements QbSubjectSubscriptionService {
    @Autowired
    private TokenService tokenService;

    /**
     * @param subjectSubscriptionVo
     * @param request
     * @description: 情报专题订阅设置
     * @author: ChenYao
     * @return: void
     * @ceateDate: 2025/1/14 下午11:27
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setSubjectSubscription(SubjectSubscriptionVo subjectSubscriptionVo, HttpServletRequest request) {
        String userId = tokenService.getUserId(request);
        if (userId == null) {
            throw new NoLoginException("用户未登录");
        }
        List<String> subjectIds = subjectSubscriptionVo.getSubjectIds();
        if (CollectionUtils.isEmpty(subjectIds)) {
            throw new ServiceException("情报专题不能为空");
        }
        // 是否订阅
        Boolean isSubscribe = subjectSubscriptionVo.getIsSubscribe();
        List<QbSubjectSubscription> list = new ArrayList<>();

        // 如果不是订阅，则删除数据
        baseMapper.delete(Wrappers.<QbSubjectSubscription>lambdaQuery()
                .eq(QbSubjectSubscription::getUserId, userId)
                .in(QbSubjectSubscription::getSubjectId, subjectIds)
        );
        // 如果是订阅，则插入数据
        if (isSubscribe) {
            for (String subjectId : subjectIds) {
                QbSubjectSubscription qbSubjectSubscription = new QbSubjectSubscription();
                qbSubjectSubscription.setUserId(userId);
                qbSubjectSubscription.setSubjectId(subjectId);
                list.add(qbSubjectSubscription);
            }
            this.saveBatch(list);
        }


    }
}




